<!--
 * @Date: 2024-06-28 14:24:38
 * @Autor: 叶世超
 * @LastEditors: 叶世超 yesc163@163.com
 * @LastEditTime: 2024-07-09 09:48:32
 * @FilePath: \reslib-web\src\views\picture\index.vue
 * @Description: 描述
 * @version: 版本
-->
<template>
  <ContentWrap>
    <!-- 搜索栏 -->
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="90px"
    >
      <el-form-item label="图片名称" prop="name">
        <el-input
          v-model="queryParams.name"
          class="!w-240px"
          clearable
          placeholder="请输入图片名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="图片尺寸" prop="size">
        <el-input
          v-model="queryParams.size"
          class="!w-240px"
          clearable
          placeholder="请输入图片尺寸"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="图片分类" prop="classify">
        <el-select
          v-model="queryParams.classify"
          class="!w-240px"
          placeholder="请选择图片分类"
          style="width: 240px"
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in classifyList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
          end-placeholder="结束日期"
          start-placeholder="开始日期"
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button plain type="primary" @click="openImageUpload">
          <Icon class="mr-5px" icon="ep:upload" />
          图片上传
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <!-- 图片列表 -->
  <ContentWrap>
    <div class="demo-image__error">
      <el-checkbox-group v-model="checked" @change="selectedPicture">
        <div class="block" v-for="(item, index) in list" :key="item">
          <span class="checkbox">
            <el-checkbox id="pictureId" :indeterminate="false" :label="item.id" name="id">
              <br />
            </el-checkbox>
            <Icon
              v-if="!item.atlas"
              class="option"
              icon="ep:edit"
              @click="updatePicture(item.id)"
            />
          </span>
          <el-image
            v-if="!item.atlas"
            fit="contain"
            :src="item.url"
            :preview-src-list="previewList"
            :initial-index="initPreview"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            @show="previewShow(index)"
          />
          <div
            v-if="item.atlas"
            @click="handleFolderClick(item)"
            class="document-box"
            title="这是一个文件夹"
          >
            <el-icon><Folder /></el-icon>
          </div>
          <span class="demonstration" style="font-size: 14px;width: 170px;text-overflow: ellipsis;">{{ item.name }}</span>
          <el-text class="demonstration" type="info" size="small">{{ item.createTime }}</el-text>
        </div>
      </el-checkbox-group>
    </div>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>
  <SubmitAuditFrom ref="submitAuditRef" @success="getList"></SubmitAuditFrom>
  <el-dialog
    v-model="showImageUploadDialogFlag"
    :title="dialogTitle"
    left
    :append-to-body="true"
    class="drag-dialog small-padding-dialog"
    width="90%"
    :before-close="closeDialog"
    :close-on-click-modal="false"
    align-center
  >
    <el-upload
      ref="upload"
      class="upload-demo"
      :http-request="saveImageUpload"
      list-type="picture"
      multiple="true"
      :show-file-list="false"
      :accept="PictureFormat"
      :before-upload="beforeAvatarUpload"
      v-if="!updated"
    >
      <el-button type="primary">点击上传</el-button>
      <div class="el-upload__tip">
        支持格式：{{ PictureFormatStr }}，图片大小不超过{{ PictureSize }}M
      </div>
    </el-upload>
    <div style="margin-top: 10px" v-if="saved">
      <div class="block-left">
        <el-form :model="pictureForm" label-width="80px" ref="pictureFormRef">
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="资源标题"
                :rules="{ required: true, trigger: ['blur', 'change'], message: '请填写资源标题' }"
                prop="name"
              >
                <el-input v-model="pictureForm.name" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="批次编号" prop="batch">
                <el-input v-model="pictureForm.batch" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="DOI">
                <el-input v-model="pictureForm.doi" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="图片来源">
                <el-input v-model="pictureForm.source" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="发布时间">
                <el-date-picker
                  v-model="pictureForm.releaseTime"
                  type="date"
                  placeholder="请选择发布时间"
                  :disabled-date="disabledDate"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="图片分类">
                <el-cascader
                  :options="classifyList"
                  v-model="pictureForm.classify"
                  placeholder="请选择图片分类"
                  :props="{ label: 'name', value: 'id' }"
                  style="width: 100%"
                  @change="selectClassify"
                >
                </el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="作者">
                <el-input v-model="pictureForm.author" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用途">
                <el-input v-model="pictureForm.useTo" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="图片尺寸">
                <el-input v-model="pictureForm.size" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="格式">
                <el-input v-model="pictureForm.format" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="适用终端">
                <el-input v-model="pictureForm.terminal" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="成图方法">
                <el-input v-model="pictureForm.generate" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="质量等级">
                <el-input v-model="pictureForm.quality" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="密级">
                <el-select v-model="pictureForm.secret" placeholder="请选择密级">
                  <el-option
                    v-for="item in secretList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="是否调修">
                <el-switch v-model="pictureForm.adjustment" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="颜色分类">
                <el-select v-model="pictureForm.color" placeholder="请选择颜色分类">
                  <el-option
                    v-for="item in colorList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="拍摄时间">
                <el-date-picker
                  v-model="pictureForm.captureTime"
                  type="date"
                  placeholder="请选择拍摄时间"
                  :disabled-date="disabledDate"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="相关地点">
                <el-input v-model="pictureForm.place" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="描述">
                <el-input type="textarea" v-model="pictureForm.remark" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="block-right">
        <el-image :src="pictureForm.url" />
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="closeDialog">关闭</el-button>
        <el-button type="primary" :disabled="!saved" @click="saveForm">保存</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog
    v-model="showImageUploadListDialogFlag"
    :title="picturesDialogTitle"
    left
    :append-to-body="true"
    class="drag-dialog small-padding-dialog"
    width="50%"
    :before-close="picturesCloseDialog"
    :close-on-click-modal="false"
    align-center
  >
    <el-upload
      v-model:file-list="fileList"
      :http-request="saveImageUploadList"
      list-type="picture"
      :on-preview="handlePictureCardPreview"
      :accept="PictureFormat"
      :on-remove="handleRemove"
      :multiple="true"
    >
      <el-button type="primary">点击上传</el-button>
      <div class="el-upload__tip">
        支持格式：{{ PictureFormatStr }}，图片大小不超过{{ PictureSize }}M
      </div>
    </el-upload>

    <br />
    <span>提示：选择图片时可按住键盘 Ctrl 键点击图片多选</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="picturesCloseDialog">关闭</el-button>
        <el-button type="primary" @click="savePicturesForm">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { Folder, FolderAdd, ArrowLeft } from '@element-plus/icons-vue'
import { ref, reactive, defineComponent } from 'vue'
import { PictureFormat, PictureSize, PictureFormatStr } from '@/utils/config'
import * as pictureApi from '@/api/picture'
import { ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import download from '@/utils/download'
import router from '@/router'
import SubmitAuditFrom from '@/views/resource/meta/SubmitAuditFrom.vue'
import { DICT_TYPE } from '@/utils/dict'
const folderAddDialogTitle = ref('新建文件夹')
const folderAddDialogRef = ref()
const batchAuditing = () => {
  if (selectedPictures.value.length === 0) {
    ElMessage.warning('请选择要送审的数据!')
    return
  }
  let ids = selectedPictures.value
  submitAuditRef.value.open(1, 0, ids)
}

const submitAuditRef = ref()
const showImageUploadListDialogFlag = ref(false)
const picturesDialogTitle = ref('批量上传')
const fileList = ref<UploadUserFile[]>([])

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const openImageUploadList = () => {
  showImageUploadListDialogFlag.value = true
  updated.value = false
  getClassify()
}
const imageDownload = async () => {
  if (selectedPictures.value.length === 0) {
    ElMessage.warning('请选择要下载的数据!')
    return
  }
  let ids = selectedPictures.value
  try {
    if (selectedPictures.value.length === 1) {
      const res = await pictureApi.download(ids[0], 1)
      download.zip(res, new Date().getTime() + '.png')
    } else {
      const res = await pictureApi.downloads(ids.join(';'), 1)
      download.zip(res, new Date().getTime() + '.zip')
    }
  } catch {}
}
const imageList = ref<File[]>([])
const saveImageUploadList = async (contents) => {
  imageList.value.push(contents.file)
}
const selectClassify = (value) => {
  pictureForm.value.classify = value[value.length - 1]
}
/**
 * 图集表单提交
 */
const savePicturesForm = async () => {
  let form = new FormData()
  imageList.value.forEach((file) => {
    console.log(file)
    form.append('fileList', file)
  })
  form.append('pid', queryParams.pid)

  const data = await pictureApi.uploadList(form)
  console.log(data)
  imageList.value = []
  fileList.value = []
  showImageUploadListDialogFlag.value = false
  getList()
}
/*
 * 批量上传弹窗
 * */
const picturesCloseDialog = () => {
  imageList.value = []
  fileList.value = []
  showImageUploadListDialogFlag.value = false
}

const queryFormRef = ref<any>()
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const previewList = ref([])
const initPreview = ref(0)
const showImageUploadDialogFlag = ref(false)
const pictureForm = ref({})
const saved = ref(false)
const updated = ref(false)
const dialogTitle = ref('图片上传')

const pictureFormRef = ref<FormInstance>()

const classifyList = ref([])

const checked = ref([])

// 下钻图集
const handleFolderClick = (rowData) => {
  console.log(rowData)
  queryParams.pid = rowData.id
  getList()
}

const updatePicture = (id) => {
  getClassify()
  showImageUploadDialogFlag.value = true
  saved.value = true
  updated.value = true
  dialogTitle.value = '图片修改'
  pictureApi.selectOne(id).then((res) => {
    pictureForm.value = res
    if (pictureForm.value.classify) {
      pictureForm.value.classify = Number(pictureForm.value.classify)
    }
  })
}

const message = useMessage()
const deleted = async () => {
  if (selectedPictures.value.length == 0) {
    ElMessage.warning('请选择要删除的数据!')
    return
  }
  try {
    await message.confirm('确定删除选中的图片吗？')
    let ids = selectedPictures.value
    await pictureApi.deleted(ids)
    await getList()
  } catch {}
}

const secretList = ref([
  {
    value: '1',
    label: '绝密'
  },
  {
    value: '2',
    label: '机密'
  },
  {
    value: '3',
    label: '秘密'
  }
])

const colorList = ref([
  {
    value: '1',
    label: '分类一'
  },
  {
    value: '2',
    label: '分类一'
  },
  {
    value: '3',
    label: '分类一'
  }
])

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: null,
  size: null,
  classify: undefined,
  createTime: [],
  type: 1,
  pid: 0,
})
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}
const previewShow = (index) => {
  initPreview.value = index
}
const openImageUpload = () => {
  showImageUploadDialogFlag.value = true
  updated.value = false
  getClassify()
}

const selectedPictures = ref([]) // 选中的数据
const selectedPicture = (value) => {
  console.log(value)
  selectedPictures.value = value
}

const getList = async () => {
  loading.value = true
  try {
    const data = await pictureApi.page(queryParams)
    list.value = data.list
    total.value = data.total
    previewList.value = []
    list.value.forEach((key, index) => {
      previewList.value.push(key.url)
    })
  } finally {
    loading.value = false
  }
}
const getClassify = async () => {
  const data = await pictureApi.getPictureClassify()
  classifyList.value = data
}
const saveImageUpload = async (content) => {
  let form = new FormData()
  console.log(content.file)
  form.append('file', content.file)
  const data = await pictureApi.upload(form)
  saved.value = true
  pictureForm.value.url = data.data.url
  pictureForm.value.size = data.data.size
  pictureForm.value.format = data.data.ext
  pictureForm.value.fileSize = data.data.fileSize
  pictureForm.value.relativePath = data.data.relativePath
  pictureForm.value.type = 1
  pictureForm.value.classtype = 1
}

const closeDialog = () => {
  if (saved.value && !updated.value) {
    ElMessageBox.confirm('现在退出将不对图片进行保存，是否继续？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      showImageUploadDialogFlag.value = false
      pictureForm.value = {}
      saved.value = false
    })
  } else {
    showImageUploadDialogFlag.value = false
    saved.value = false
  }
}

const handleQuery = () => {
  getList()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/**
 * 表单提交
 */
const saveForm = () => {
  pictureFormRef.value.validate(async (valid) => {
    console.log(valid)
    if (valid) {
      console.log(pictureForm.value)
      pictureForm.value.pid = queryParams.pid
      pictureApi.savePicture(pictureForm.value).then((res) => {
        console.log(res)
        showImageUploadDialogFlag.value = false
        saved.value = false
        pictureForm.value = {}
        getList()
      })
    }
  })
}
//资源回收站
const recycle = () => {
  router.push({
    path: '/resource/picture/recycle'
  })
}
//新建文件夹
const handleFolderAdd = () => {
  folderAddDialogRef.value.open('打开 dialog')
}
// 从图集返回上一层
const handleReturn = () => {
  // delete queryParams.pid
  queryParams.pid = 0
  getList()
}
/** 初始化 **/
onMounted(() => {
  getList()
  getClassify()
})
</script>
<style lang="scss" scoped>
.block-left {
  padding: 30px 20px;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  display: inline-block;
  width: 70%;
  box-sizing: border-box;
  vertical-align: top;
}
.block-right {
  padding: 30px 20px;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  display: inline-block;
  width: 30%;
  box-sizing: border-box;
  vertical-align: top;
}
.dialog-footer {
  text-align: center;
}
.body {
  margin: 0;
}
.demo-image__error .block {
  padding: 30px 20px;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  display: inline-block;
  width: 20%;
  box-sizing: border-box;
  vertical-align: top;
  height: 330px;
}
.demo-image__error .block .more {
  float: right;
  color: #8c8a8a;
}
.demo-image__error .demonstration {
  text-align: left;
  float: left;
  color: var(--el-text-color-secondary);
  margin-top: 10px;
  margin-bottom: 10px;
}
.demo-image__error .datetime {
  text-align: left;
  display: block;
  color: #666666;
  font-size: 14px;
  margin-top: 10px;
}
.demo-image__error .checkbox {
  text-align: left;
  display: block;
  font-size: 14px;
  margin-bottom: 10px;
}
.demo-image__error .el-image {
  max-width: 300px;
  max-height: 200px;
  width: 100%;
  height: 100%;
}

.demo-image__error .image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.option {
  float: right;
  cursor: pointer;
  color: #8c8e91;
  display: flex;
  align-items: center;
}
.document-box {
  cursor: pointer;
  max-width: 300px;
  max-height: 200px;
  height: 200px;
  font-size: 150px;
  line-height: 200px;
  color: #f5617f;
}
</style>
